package com.xo.xodemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.xo.xodemo.controller.system.UserController;
import com.xo.xodemo.mapper.db1.RoleMapper;
import com.xo.xodemo.mapper.db1.UserMapper;
import com.xo.xodemo.model.Role;
import com.xo.xodemo.model.BaseUser;
import com.xo.xodemo.service.UserService;

import com.xo.xodemo.springsecurityconfig.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserController userController;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        try {
            //验证用户在职状态，如果为离职状态不允许登录
            Integer isIncumbency =  userController.selectIsIncumbencyByUserName(username);
            if (isIncumbency == 0){
                return null;
            }

            //获取用户信息，如果没有用户信息直接返回
            BaseUser baseUser = userMapper.loadUserByUsername(username);
            if(baseUser == null){
                return null;
            }
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            List<Role> roles = roleMapper.findRoleByUserPosition(baseUser.getPositionId());
            for(Role role: roles){
                authorityList.add(new SimpleGrantedAuthority(role.getRoleName()));
            }

            CustomUserDetails userDetails = new CustomUserDetails(baseUser.getUsername(), baseUser.getPassword(),baseUser.getRealName(),baseUser.getDepartmentId(), baseUser.getPositionId(), baseUser.getEmployeeNumber(), authorityList);
            return userDetails;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
